package com.example.tiantian.process;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.regex.Pattern;

import com.example.tiantian.R;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.ActivityManager.MemoryInfo;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Size;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

public class HardwareFragment extends Fragment {
    TelephonyManager telManager;
    ActivityManager actManger;
    PackageManager packManager;
    WifiManager wifiManager;
    WifiInfo wifiInfo;

    ExpandableListView listView;

    MyMap<MyMap<String>> map;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        map = new MyMap<MyMap<String>>();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        telManager = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        actManger = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
        packManager = activity.getPackageManager();
        wifiManager = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
        wifiInfo = wifiManager.getConnectionInfo();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_process_info, null);
        listView = (ExpandableListView) v.findViewById(R.id.process_info_list);
        getBaseInfo();
        getCPUInfo();
        getMemoryInfo();
        getCameraInfo();
        getScreenInfo();
        getNetInfo();
        InfoAdapter adapter = new InfoAdapter(getActivity(), map);
        listView.setAdapter(adapter);
        return v;
    }

    private void getNetInfo() {
        MyMap<String> netInfo = new MyMap<String>();

        netInfo.put(getString(R.string.process_info_net_wifi_ssid), wifiInfo.getSSID());
        int ip = wifiInfo.getIpAddress();
        String ip_str = Formatter.formatIpAddress(ip);
        netInfo.put(getString(R.string.process_info_net_wifi_ip), ip_str);
        netInfo.put(getString(R.string.process_info_net_wifi_speed), wifiInfo.getLinkSpeed() + "");
        netInfo.put(getString(R.string.process_info_net_wifi_mac), wifiInfo.getMacAddress());

        map.put(getString(R.string.process_info_net), netInfo);
    }

    @SuppressWarnings("deprecation")
    private void getScreenInfo() {
        MyMap<String> screenInfo = new MyMap<String>();
        Display display = getActivity().getWindowManager().getDefaultDisplay();
        screenInfo.put(getString(R.string.process_info_screen_size), display.getWidth() + "*" + display.getHeight());
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        screenInfo.put(getString(R.string.process_info_screen_density), metrics.density + "");
        screenInfo.put(getString(R.string.process_info_screen_multi_touch_type),
                packManager.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH) + "");
        map.put(getString(R.string.process_info_screen), screenInfo);
    }

    private void getCameraInfo() {
        MyMap<String> cameraInfo = new MyMap<String>();
        Camera camera = Camera.open();
        Camera.Parameters params = camera.getParameters();
        List<Size> sizes = params.getSupportedPictureSizes();
        for (Size s : sizes) {
            System.out.println(s.width + "*" + s.height);
        }
        Size maxsize = sizes.get(0);
        camera.release();
        cameraInfo.put(getString(R.string.process_info_camera_size), maxsize.width + "*" + maxsize.height);
        String flashMode = params.getFlashMode();
        camera.release();
        cameraInfo.put(getString(R.string.process_info_camera_flash), flashMode == null ? "false" : "true");

        map.put(getString(R.string.process_info_camera), cameraInfo);
    }

    private void getMemoryInfo() {
        MyMap<String> memoryInfo = new MyMap<String>();
        // 获取可用内存
        MemoryInfo minfo = new MemoryInfo();
        actManger.getMemoryInfo(minfo);
        long size = minfo.availMem;
        memoryInfo.put(getString(R.string.process_info_memory_avail), Formatter.formatFileSize(getActivity(), size));
        // 获取总内存大小
        String filename = "/proc/meminfo";
        String content = "";
        String result = "";
        BufferedReader br;
        try {
            br = new BufferedReader(new FileReader(filename));
            content = br.readLine();
            long total = Long.parseLong(content.substring(content.indexOf(":") + 1, content.indexOf("k")).trim());
            total *= 1024;
            result = Formatter.formatFileSize(getActivity(), total);
        } catch (FileNotFoundException e) {
            Log.e(getActivity().getPackageName(), e.toString());
        } catch (IOException e) {
            Log.e(getActivity().getPackageName(), e.toString());
        }
        memoryInfo.put(getString(R.string.process_info_memory_total), result);
        // 获取SD卡容量
        File dir = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(dir.getPath());
        long blocksize = stat.getBlockSize();// 获取每个block的大小
        long blockcount = stat.getAvailableBlocks(); // 获取block的个数
        // stat.getAvailableBlocks();//可用的数量（剩余数量）
        long sdsize = blocksize * blockcount;
        memoryInfo.put(getString(R.string.process_info_memory_sd), Formatter.formatFileSize(getActivity(), sdsize));

        map.put(getString(R.string.process_info_memory), memoryInfo);
    }

    private void getCPUInfo() {
        MyMap<String> cpuInfo = new MyMap<String>();
        try {
            // CPU型号
            BufferedReader br = new BufferedReader(new FileReader("/proc/cpuinfo"));
            String content = br.readLine();
            cpuInfo.put(getString(R.string.process_info_cpu_name), content.split(":")[1].trim());
            br.close();
            // cpu核心数量
            File dir = new File("/sys/devices/system/cpu");
            File files[] = dir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File pathname) {
                    // 正则表达式 定义个规则 文件明必须是 cpu0 cpu1 cpu2.....
                    if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                        return true;
                    }
                    return false;
                }

            });
            cpuInfo.put(getString(R.string.process_info_cpu_core_number), "" + files.length);

            // CPU频率
            ProcessBuilder cmd;
            String freg = "";
            String[] args = { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq" };
            cmd = new ProcessBuilder(args);
            Process process = cmd.start();
            InputStream in = process.getInputStream();
            byte[] re = new byte[24];
            while (in.read(re) != -1) {
                freg = freg + new String(re);
            }
            in.close();
            cpuInfo.put(getString(R.string.process_info_cpu_max_freg), freg);

            args = new String[] { "/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq" };
            cmd = new ProcessBuilder(args);
            process = cmd.start();
            in = process.getInputStream();
            re = new byte[24];
            freg = "";
            while (in.read(re) != -1) {
                freg = freg + new String(re);
            }
            in.close();
            cpuInfo.put(getString(R.string.process_info_cpu_min_freg), freg);

            FileReader fr = new FileReader("/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
            br = new BufferedReader(fr);
            freg = br.readLine().trim();
            cpuInfo.put(getString(R.string.process_info_cpu_current_freg), freg);
            br.close();
        } catch (FileNotFoundException e) {
            Log.e(getActivity().getPackageName(), e.toString());
        } catch (IOException e) {
            Log.e(getActivity().getPackageName(), e.toString());
        }
        map.put(getString(R.string.process_info_cpu), cpuInfo);
    }

    private void getBaseInfo() {
        MyMap<String> deciceInfo = new MyMap<String>();
        deciceInfo.put(getString(R.string.process_info_base_device_name), Build.MODEL);
        deciceInfo.put(getString(R.string.process_info_base_system_version), Build.VERSION.RELEASE);
        deciceInfo.put(getString(R.string.process_info_base_device_id), telManager.getDeviceId());
        deciceInfo.put(getString(R.string.process_info_base_isp), telManager.getNetworkOperatorName());
        deciceInfo.put(getString(R.string.process_info_base_phone_number), telManager.getLine1Number());
        deciceInfo.put(getString(R.string.process_info_base_is_root), isRoot() ? "Yes" : "No");
        map.put(getString(R.string.process_info_base), deciceInfo);
    }

    /**
     * @return 设备是否Root
     */
    public boolean isRoot() {
        Process process = null;
        DataOutputStream dos = null;
        try {
            process = Runtime.getRuntime().exec("su");// 开启进程
            dos = new DataOutputStream(process.getOutputStream());
            dos.writeBytes("ls /data/\n");// 写入内容 测试是否root
            dos.writeBytes("exit\n");
            dos.flush();
            process.waitFor();
        } catch (Exception e) {
            Log.e(getActivity().getPackageName(), e.toString());
            return false;// 没有root
        } finally {
            try {
                if (dos != null) {
                    dos.close();
                }
                process.destroy();
            } catch (Exception e) {
                Log.e(getActivity().getPackageName(), e.toString());
            }
        }
        return true;

    }
}
